import { createSlice, PayloadAction, createAsyncThunk } from '@reduxjs/toolkit'
import axios from 'axios'
import { checkout } from '../shoppingCart/slice'

interface OrderState {
  loading: boolean,
  error: null | unknown,
  currentOrder: any
}

// 初始化数据
const initialState: OrderState = {
  loading: false,
  error: null,
  currentOrder: null // 新订单创建后的数据
}

export const placeOrder = createAsyncThunk(
  "order/placeOrder",
  async (parameters: {jwt: string, orderId: string}, thunkAPI) => {
    const { data: {data} } = await axios.get('https://mock.mengxuegu.com/mock/61c70e2ebba8817f8a413580/tourism_website/touristRoute')
    console.log("详情", data)
    return data
  }
)

export const orderSlice = createSlice({
  name: 'order', // 命名空间名称
  initialState, // 初始化数据
  reducers: {}, // 这里的reducer是把action和reducer捆绑在了一起.所以不需要在单独定义action,这里的reducer是个对象
  extraReducers: {
    [placeOrder.pending.type]: (state) => {
      // 原始写法
      // return { ...state, loading: true }
      state.loading = true  // immer
    },
    // reducer中已经提前定义好了action的参数
    // 请求成功
    [placeOrder.fulfilled.type]: (state, action) => {
      state.loading = false
      state.currentOrder = action.payload
      state.error = null
    },
    // 请求失败
    [placeOrder.rejected.type]: (state, action: PayloadAction<unknown | null>) => {
      state.loading = false
      state.error = action.payload
    },
    [checkout.pending.type]: (state) => {
      // 原始写法
      // return { ...state, loading: true }
      state.loading = true  // immer
    },
    // reducer中已经提前定义好了action的参数
    // 请求成功
    [checkout.fulfilled.type]: (state, action) => {
      state.loading = false
      state.currentOrder = action.payload
      state.error = null
    },
    // 请求失败
    [checkout.rejected.type]: (state, action: PayloadAction<unknown | null>) => {
      state.loading = false
      state.error = action.payload
    }
  }
})